package in.muton.edushare.components.messaging.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class EscapeHTML {
	private static String escapeLTGT(String input){
	    final StringBuilder result = new StringBuilder();
	    final StringCharacterIterator iterator = new StringCharacterIterator(input);
	    char character =  iterator.current();
	    while (character != CharacterIterator.DONE ){
	      if (character == '<') {
	        result.append("&lt;");
	      }
	      else if (character == '>') {
	        result.append("&gt;");
	      }
	      else {
	        result.append(character);
	      }
	      character = iterator.next();
	    }
	    return result.toString();
	}
	
	private static String urlDetector(String input){
		String [] parts = input.split("\\s");
		String output = "";
        // Attempt to convert each item into an URL.   
        for( String item : parts ) try {
            URL url = new URL(item);
            output += "<a target='_blank' href=\"" + url + "\">"+ url + "</a> ";
        } catch (MalformedURLException e) {
        	output += item+" ";
        }
        return output;
	}

	public static String processInputString(String input){
		return urlDetector(escapeLTGT(input));
	}
}
